<template>
  <div>
    <el-dialog
      :title="activityTitle"
      :visible.sync="selfShow"
      top="2rem"
      width="80%">
      <el-table
        :data="items"
        v-loading="loading"
        element-loading-text="数据载入中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255,255,255, 0.4)"
        style="width:100%">
        <el-table-column
          label="标题">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-input v-model="scope.row.title"></el-input>
            </template>
            <template v-else>
              {{scope.row.title}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="上车地址">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-input :disabled="true" v-model="scope.row.address">
                <el-button @click="showMap(scope.row)" slot="append">地图选择</el-button>
              </el-input>
            </template>
            <template v-else>
              {{scope.row.address}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="上车时间">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-date-picker
                v-model="scope.row.set_out_time"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择上车时间"
                :picker-options="pickerOptions"
                default-time="07:00:00">
              </el-date-picker>
            </template>
            <template v-else>
              {{scope.row.set_out_time}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="人数限制">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-input type="number" v-model="scope.row.sign_up_limit"></el-input>
            </template>
            <template v-else>
              {{scope.row.sign_up_limit}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.edit"
              size="little"
              @click="edit(scope.row)"
              type="primary">保存</el-button>
            <el-button
              size="little"
              v-else
              @click="scope.row.edit = true"
              type="warning">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selfShow = false">取 消</el-button>
        <el-button type="primary" @click="showCreateCollectionPoint = true">添加集合点</el-button>
      </span>
    </el-dialog>
    <el-dialog ref="amap" top="2rem" title="地图选点" :visible.sync="showMapStatus">
      <div class="search">
        <el-input v-model="marker.searchAddress" placeholder="请输入详细地址" class="input-with-select">
          <el-button @click="getLocationByAddress" slot="append" type="success" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <el-amap
        :events="events"
        :zoom="zoom"
        ref="map"
        :center="marker.position"
        :amap-manager="amapManager"
        :plugin="plugin"
        class="amap"
        vid="amapDemo">
        <el-amap-marker
          :position="marker.position"
          vid="index"></el-amap-marker>
      </el-amap>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showMapStatus = false">取 消</el-button>
        <el-button type="primary" @click="getAddress">确定</el-button>
      </div>
    </el-dialog>
    <template>
      <el-dialog
        title="添加集合点"
        :close-on-click-modal="false"
        :show-close="false"
        top="2rem"
        :visible.sync="showCreateCollectionPoint">
        <el-form :model="createCollectionData">
          <el-form-item label="集合点" label-width="100px">
            <el-select v-model="createCollectionData.id" filterable placeholder="输入关键词搜索" style="width: 220px">
              <el-option
                v-for="(item, idx) in collectionPointItems"
                :key="'create_collection_point_' + idx"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人数限制" label-width="100px">
            <el-input
              type="number"
              v-model="createCollectionData.sign_up_limit"
              style="max-width: 220px">
            </el-input>
          </el-form-item>
          <el-form-item label="上车时间" label-width="100px">
            <el-date-picker
              v-model="createCollectionData.set_out_time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择上车时间"
              :picker-options="pickerOptions"
              default-time="07:00:00">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showCreateCollectionPoint = false">取 消</el-button>
          <el-button type="primary" @click="submitForCreateCollectionPoint">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </div>
</template>
<script>
import {amapManager} from 'vue-amap'
export default {
  props: {
    cityId: {
      type: Number
    },
    groupStageId: {
      type: Number
    },
    show: {
      type: Boolean,
      default: false
    },
    activityTitle: {
      type: String,
      default: '集合点列表'
    }
  },
  data () {
    return {
      collectionPointItems: [],
      showCreateCollectionPoint: false,
      createCollectionData: {
        id: '',
        sign_up_limit: '',
        set_out_time: ''
      },
      selfItem: {},
      amapManager,
      zoom: 12,
      events: {
        init: (o) => {
          // console.log(o)
        },
        click: (e) => {
          this.marker.position = [e.lnglat.lng, e.lnglat.lat]
          this.getAddressByLocation()
        }
      },
      plugin: ['ToolBar'],
      showMapStatus: false,
      marker: {
        position: [],
        searchAddress: ''
      },
      pickerOptions: {},
      items: [],
      loading: false,
      selfShow: false
    }
  },
  watch: {
    show (val) {
      if (val) {
        this.getItems()
        this.getCollectionPointItems()
      }
      this.selfShow = val
    },
    selfShow (val) {
      if (!val) {
        this.$emit('update:show', val)
      }
    }
  },
  methods: {
    /**
     *  添加集合点
     */
    submitForCreateCollectionPoint () {
      this.collectionPointItems.map(item => {
        if (item.id === this.createCollectionData.id) {
          Object.assign(this.createCollectionData, item, {activity_group_stage_id: this.groupStageId})
        }
      })
      delete this.createCollectionData.id
      this.showLoading()
      this
        .$api
        .activity
        .collectionPointCreate(this.createCollectionData)
        .then(r => {
          this.toast('添加成功')
          this.showCreateCollectionPoint = false
          this.createCollectionData = {
            id: '',
            sign_up_limit: '',
            set_out_time: ''
          }
          this.getItems()
        })
    },
    /**
     * 编辑集合点
     */
    edit (data) {
      data.edit = false
      this
        .$api
        .activity
        .collectionPointEdit(data)
        .then(r => {
          console.log('编辑成功', r)
        })
    },
    /**
     *  显示地图
     */
    showMap (item) {
      console.log(item)
      this.selfItem = item
      this.showMapStatus = true
      this.marker.searchAddress = item.address
      this.marker.position = [item.lng, item.lat]
    },
    /**
     *  从地图获取信息
     */
    getAddress () {
      this.items = this.items.map(item => {
        if (this.selfItem.id === item.id) {
          item.lng = this.marker.position[0]
          item.lat = this.marker.position[1]
          item.title = this.marker.searchAddress
          item.address = this.marker.searchAddress
        }
        return item
      })
      this.showMapStatus = false
    },

    /**
     *  @purpose 获取集合点信息
     */
    getCollectionPointItems () {
      this.collectionPointItems = []
      this
        .$api
        .collectionPoint
        .itemsByCity(this.cityId)
        .then(r => {
          if (r.length < 1) {
            this.toast('该市区暂无集合点,请先添加')
            return false
          }
          this.collectionPointItems = r
        })
    },
    /**
     * 经纬度解析
     */
    getLocationByAddress () {
      if (!this.marker.searchAddress) {
        this.toast('请输入详细地址!', 'warning')
        return false
      }
      this.showLoading()
      this
        .$api
        .map
        .getLocationByAddress(this.marker.searchAddress, this.selfItem.city_name)
        .then(r => {
          if (r.length < 1) {
            this.toast('没有搜索到相关地址信息,换个地址试试..!', 'warning')
            return false
          }
          this.marker.searchAddress = r[0].formatted_address
          this.marker.position = r[0].location.split(',')
          // r.map(item => {
          //   this.markers.push({
          //     searchAddress: item.formatted_address,
          //     position: item.location.split(','),
          //     events: {
          //       click: (e) => {
          //         console.log(e)
          //       }
          //     }
          //   })
          // })
        })
    },
    /**
     * 地址逆解析
     */
    getAddressByLocation () {
      let auto = setTimeout(() => {
        this.showLoading()
      }, 2000)
      this
        .$api
        .map
        .getAddressByLocation(this.marker.position.join(','))
        .then(r => {
          clearTimeout(auto)
          this.marker.searchAddress = r.formatted_address
        })
        .catch(() => {
          clearTimeout(auto)
        })
    },
    /**
     * @purpose 获取列表数据
     */
    getItems () {
      this.loading = true
      this
        .$api
        .activity
        .collectionPointItems(this.groupStageId)
        .then(r => {
          this.loading = false
          this.items = r.map(item => {
            item.edit = false
            return item
          })
        })
    }
  },
  created () {
    this.pickerOptions = Object.assign({}, this.pickerOptions, {
      disabledDate: (time) => {
        return (time.getTime() + 3600 * 24) < this.getDayStartTimeStamp()
      }
    })
  }
}
</script>
<style scoped lang="sass">
  .collection-point
    width: 100%
    height: 100%
  .search
    width: 100%
    margin: 10px 0 20px 0
  .amap
    height: 500px
  .search-box
    position: absolute
    top: 25px
    left: 20px
  .amap-page-container
    position: relative
</style>
